<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//$path = $_SERVER['DOCUMENT_ROOT'].'/stellogoogle/eventsmanager/MySQLAdapter.php';
include_once('MySQLAdapter.php');
include_once './server/model/database_tables_handler.php';
//include_once "object_auto_loader.php";
 include_once "object_auto_loader.php";
   class controller
                {

             private $autoLoader;
             private $db_handler;
public function  __construct() {


//$config = array("localhost","root","password.1","eventsmanager_v2");
//////Get a singleton instance of the adapter
//$adapter = MySQLAdapter::getInstance($config);
//$adapter->connect();
 //$this->autoLoader = new object_auto_loader();
     $a = new theme_roller(null);
   //  $this->db_handler = new database_tables_handler();
    $this->dispatch('home');
    }

   public function dispatch($action) {

///Get action from query string and set default to home

///Convert the action into a method
        $method = $this->__getMethod($action);
///Return the template determined by the method resulting from action
        return $this->$method();
    }

    /*!
     * \brief checks if the action exists
     *  \return A boolean value
     * \param action a string containing the action
     */

    private function __validAction(& $action) {
///Checks if the methods exists and returns a simple boolean value
        if (method_exists($this, "__" . $action)) {
/// Method exists in a member function of the controller class from the chisimba core
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /*!
     * \brief Get an action
     * \param action A string
     *  \return the method that corresponds to the action
     */

    private function __getMethod(& $action) {
///Checks using __validAction if the action exists and returns the corresponding method
        if ($this->__validAction($action)) {
            return "__" . $action;
        } else {
///If methos does not exist return the method __actionError which returns
///a template displaying an error
            return "__actionError";
        }
    }

    private function __diverter()
    {
          $path =   $_SERVER['DOCUMENT_ROOT'].'/stellogoogle/eventsmanager/server/view/test.php';
          return include_once($path);
    }

    private function __adminHome()
    {
           new object_auto_loader();
        return include_once("server/view/adminHome.php");
    }
    private function __home()
    {
       return include_once("server/view/home.php");
      }

      private function __testHome()
      {
     
/* Redirect to a different page in the current directory that was requested */

          $action = $_GET["action"];
        return include_once("server/view/home.php");
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'server/view/home.php';
    return include_once("http://$host$uri/$extra?action=$action");
header("Location: http://$host$uri/$extra?action=$action");
exit;
      }

      private function __addNewEvent()
      {
        $dbtableHandler = new database_tables_handler();
          $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
$image_id = $dbtableHandler->getLastInsertIDForImage();
     
       // echo $parameters['eventCoordinates'];
        $eventName = $parameters['eventName'];
      $eventDescription = $parameters['eventDescription'];
       $eventWebsite = $parameters['eventWebsite'];
        $eventAddress = $parameters['eventAddress'];
       // echo $eventType = str_replace(",", " ", $parameters['eventType']). "<br>";
           $eventType =  $parameters['eventType'];
        $eventCoordinatesArray = json_decode($parameters['eventCoordinates'],true);
        $eventCoordinatesArray[0]['eventLatitude'];
        $eventCoordinatesArray[0]['eventLongitude'];

$newEventID = $dbtableHandler->insertEvent($_SESSION['user_id'], $eventName, $eventAddress, $eventDescription, $eventType, $eventCoordinatesArray[0]['eventLatitude'],$eventCoordinatesArray[0]['eventLongitude'], $eventWebsite,'',$image_id);

//$newEventID = $dbtableHandler->insertEvent($_SESSION['user_id'], $eventName, $eventAddress, $eventDescription, $eventType, $eventCoordinatesArray[0]['eventLatitude'],$eventCoordinatesArray[0]['eventLongitude'], $eventWebsite,'',);
$activityTimesArray = json_decode($parameters['serviceTimes'],true);

                      foreach ($activityTimesArray as $thisActivityTime) {
$dbtableHandler->insertActivity($newEventID, $thisActivityTime['startHour'], $thisActivityTime['startMin'], $thisActivityTime['endHour'], $thisActivityTime['endMin'], $thisActivityTime['eventName'], $thisActivityTime['eventDescription'],$thisActivityTime['eventRequirements']);
//                          echo $thisActivityTime['startHour']."<br>";
//                          echo $thisActivityTime['startMin']."<br>";
//                          echo $thisActivityTime['endHour']."<br>";
//                          echo $thisActivityTime['endMin']."<br>";
//                            echo $thisActivityTime['eventName']."<br>";
//                          echo $thisActivityTime['eventDescription']."<br>";
//                           echo $thisActivityTime['eventRequirements']."<br>";
        }

        echo "1sadasd";
      }
      private function __addNewUser()
      {
       //echo "yes";
       $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
      $dbtable = new database_tables_handler();
      $userData = array(null,$parameters['firstName'],$parameters['lastName'],$parameters['userName'],$parameters['formPassword'],$parameters['formEmail']);
       if($parameters[userType] == 'customer')
       {
                     if($dbtable->CUsernameAvailability($parameters['userName']))
           {
               $insertion_id =  $dbtable->registerCustomerUser($userData);
           }
           else
           {
               echo "Error. Username already exists.";
               return false;
           }


       }
       else
       {

           if($dbtable->BUsernameAvailability($parameters['userName']))
           {
              $insertion_id =  $dbtable->registerBusinessUser($userData);
           }
           else
           {
               echo "Error. Username already exists.";
               return false;
           }
           
       }

echo 1;
      }

      private function __setSelectedTheme()
      {
                        $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
                 new object_auto_loader();

                $selectTheme =  $parameters['selectedTheme'];
                if ($selectTheme != null)
                {
                                 $themeRollerView = new theme_roller($selectTheme);
                                 $themeSetter = new admin_page_handler();
                             echo  $themeSetter->setNewTheme($selectTheme);
             //   $themeRollerView->createThemeViewer();
                }
                else
                {
                    "Error. Theme does not exist";
                }
      }

      private function __viewSelectedTheme()
      {
                $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
                 new object_auto_loader();

                $selectTheme =  $parameters['selectedTheme'];
                if ($selectTheme != null)
                {
                                 $themeRollerView = new theme_roller($selectTheme);
                                 $a = new admin_page_handler();
                }
                else
                {
                    "Error. Theme does not exist";
                }

      }
      private function __updateBUserDetails()
      {
                 $dbtableHandler = new database_tables_handler();
          $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
          if ($parameters == null)
          {
              echo "Error. Update Uer Details Parameters have not been received.";
          }
         $fname =  $parameters['firstName'];
         $lname = $parameters['lastName'];
         $uname =  $parameters['userName'];
         $pword =  $parameters['formPassword'];
         $uemail =  $parameters['formEmail'];
               if(isset($_SESSION['user_id']))
      {

       echo  $dbtableHandler->updateBUserDetails($_SESSION['user_id'],$fname,$lname,$uname,$pword,$uemail);
      }
      else
      {
           echo "Error. You have logged on illegally. Session varables are not present.";
      }
      }

      private function __businessHome()
      {
         new object_auto_loader();
          $path =   $_SERVER['DOCUMENT_ROOT'].'/stellogoogle/eventsmanager/server/view/business.php';
          return include_once($path);
          $host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'server/view/test.php';
//return include_once("http://$host$uri/$extra");
header("Location: http://$host$uri/$extra");
//exit;
      }

      private function __getBusinessEventMap()
      {
              $path =   $_SERVER['DOCUMENT_ROOT'].'/stellogoogle/eventsmanager/server/view/business_google_map.php';
          return include_once($path);
      }

      private function __loginUser()
      {
     $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
     $dbtable = new database_tables_handler();
     $autenticationSuccess = null;
     if ($parameters['loginType'] == "customer")
     {
        if(!$dbtable->authenticateCustomerUser($parameters['loginName'],$parameters['loginPassword']))
        {
            echo "Error. Customer User does not exist.";
            $autenticationSuccess = false;
        }
        else
        {
   //session_start();
            $autenticationSuccess = true;
   $userDetailsArray = $dbtable->getCustomerUserDetails($parameters['loginName']);


    $_SESSION['user_uname'] = $parameters['loginName'];
    $_SESSION['user_fname'] =   $userDetailsArray['cuser_fname'];
         $_SESSION['user_lname'] =  $userDetailsArray['cuser_lname'];
        $_SESSION['user_email'] = $userDetailsArray['cuser_email'];
        $_SESSION['user_id'] = $userDetailsArray['cuser_id'];
        if ($_SESSION['user_id'] == 1)
        {
         echo 2;
         return 1;
        }

        }
     }
     else
     {
        if(!$dbtable->authenticateBussinessUser($parameters['loginName'],$parameters['loginPassword']))
        {
            echo "Error. Business User does not exist.";
            $autenticationSuccess = false;
        }
        else
        {
  $autenticationSuccess = true;
   $userDetailsArray = ($dbtable->getBusinessUserDetails($parameters['loginName']));
    $_SESSION['user_uname'] = $parameters['loginName'];
       $_SESSION['user_pword'] = $parameters['loginPassword'];
   $_SESSION['user_fname'] = $userDetailsArray['buser_fname'];
         $_SESSION['user_lname'] = $userDetailsArray['buser_lname'];
         $_SESSION['user_email'] = $userDetailsArray['buser_email'];
       $_SESSION['user_id'] = $userDetailsArray['buser_id'];
        if ($_SESSION['user_id'] == 1)
        {
         echo 2;
         return 1;
        }
      
        }
     }
if ($autenticationSuccess)
{
    //$this->dispatch('businessHome');
    echo 1;
}

      }

      private function __deleteEvent()
      {
     $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
     echo $eventID = $parameters['eventID'];
     $dbtable = new database_tables_handler();
      }

      private function __getDetailsForEvent()
      {
           new object_auto_loader();
          $eventDetailsGetter = new event_details_viewer();
          $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
            $eventID = $parameters['eventID'];
         
           echo $eventDetailsGetter->showDetailedContentForEvent($eventID);
      }

            private function __customerHome()
      {
          new object_auto_loader();
                return include_once("server/view/customer.php");
      }

      private function __getActivites()
      {
            $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
            $eventID = $parameters[eventID];
                $dbtable = new database_tables_handler();

                }

                private function __getVacinityEvents()
                {
      new object_auto_loader();
                    $parameters = isset($_REQUEST['parameters']) ? $_REQUEST['parameters'] : null;
     if ($parameters != null)
     {
         $vacinityCoordinates = new vacinity_events_handler();
echo $vacinityCoordinates->getVacinityEvents( $parameters['eventLat'],  $parameters['eventLong']);
     }
     else
     {
    echo "Error. Parameters for vacinity events are not set.";
     }

                }


                }
?>
